package com.example.onion.hxchat.activity;


import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.databean.Msg;
import com.example.onion.hxchat.mvvm.ApplyViewModel;
import com.example.onion.hxchat.mvvm.InfoViewModel;
import com.example.onion.hxchat.mvvm.MessageViewModel;
import com.example.onion.hxchat.mvvm.TeamNotificationViewModel;
import com.example.onion.hxchat.mvvm.UserViewModel;
import com.example.onion.hxchat.mvvm.WcFriendViewModel;
import com.example.onion.hxchat.room.entity.Apply;
import com.example.onion.hxchat.room.entity.Friend;
import com.example.onion.hxchat.room.entity.Info;
import com.example.onion.hxchat.room.entity.TeamNotification;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.test.TestCameraActivity;
import com.example.onion.hxchat.test.TestDefineMessage;
import com.example.onion.hxchat.test.TestSQLiteActivity;
import com.example.onion.hxchat.thread.PlayUserDetailThread;
import com.example.onion.hxchat.thread.PlayUserImg;
import com.example.onion.hxchat.util.HttpUtils;
import com.example.onion.hxchat.util.ImgDownUtil;
import com.example.onion.hxchat.util.ImgUtil;
import com.example.onion.hxchat.util.MyLocalDatabaseHelper;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.myteam.R;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;

/**
 * wc的测试入口主活动，到时候还需要一些代码搬到最终的主活动去
 * 含version
 * 等待函数化获取userName,需要修改 368
 */
public class MainActivityWC extends AppCompatActivity implements View.OnClickListener, EMMessageListener, EMContactListener {

    private Button bt;
    private MyLocalDatabaseHelper dbHelper;
    private static final String TAG = "MainActivityWC";
    private Button comment_btn;
    private Button testTanBtn;
    private Button testDetailBtn;//测试详细信息页面
    private Button queryBtn;//测试详细信息页面
    private String accountId;//保存的登录的用户的id
    private int version = 4;
    private InfoViewModel infoViewModel;
    private MessageViewModel messageViewModel;
    private WcFriendViewModel friendViewModel;
    private ApplyViewModel applyViewModel;
    ImageView imageView ;
    private TeamNotificationViewModel teamNotificationViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_chat_enter);
        Toolbar toolbar = findViewById(R.id.main_wc_activity_toolbar);
        setSupportActionBar(toolbar);
        bt = findViewById(R.id.btn);
        comment_btn = findViewById(R.id.comment_btn);
        testTanBtn = findViewById(R.id.test_Tab_Btn);
        testDetailBtn = findViewById(R.id.test_more_detail_Btn);
        queryBtn = findViewById(R.id.main_query_btn);
        imageView =findViewById(R.id.test_dowmloadImg_Imgview);
        bt.setOnClickListener(this);
        comment_btn.setOnClickListener(this);
        testTanBtn.setOnClickListener(this);
        testDetailBtn.setOnClickListener(this);
        queryBtn.setOnClickListener(this);
        accountId = PassWordHelp.readPassword(MainActivityWC.this)[0];
        // messageViewModel = new ViewModelProvider(this).get(MessageViewModel.class);
        dbHelper = new MyLocalDatabaseHelper(this, "local.db", null, version);
        infoViewModel = new ViewModelProvider(this).get(InfoViewModel.class);
        friendViewModel = new ViewModelProvider(this).get(WcFriendViewModel.class);
        applyViewModel = new ViewModelProvider(this).get(ApplyViewModel.class);
        teamNotificationViewModel = new ViewModelProvider(this).get(TeamNotificationViewModel.class);
        infoViewModel.insertInfo(new Info("1234", "last info,用来发信息测试，以后要删", "1234", accountId));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
//            case R.id.info_search:
//                Log.d("InfoActivity", "搜索");
//                Toast.makeText(InfoActivity.this, "搜索", Toast.LENGTH_SHORT).show();
//                break;
            case R.id.main_toolbar_logout://退出登录的选项
                Log.d("MainActivity", "退出登录");
                logout();
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 集成环信退出登录 EMClient.getInstance().logout(true)；
     * 顺便实现删除保存的登录的用户的账号，完成LoginActivity类说明的功能
     */
    private void logout() {
        //将空值的用户账户和密码保存，覆盖先前的数据实现清除账户数据，
        // 以便可以通过PassWordHelp能否获取数据判断用户登录状态
        PassWordHelp.savePassword(MainActivityWC.this, "", "", false);
        String accountId = PassWordHelp.readPassword(MainActivityWC.this)[0];
        String pwd = PassWordHelp.readPassword(MainActivityWC.this)[1];
        Log.e("MainActivityWC", "保存null之后获取的accountId" + accountId);
        Log.e("MainActivityWC", "保存null之后获取的pwd" + pwd);
        EMClient.getInstance().logout(true);
        Intent intent = new Intent(MainActivityWC.this, LoginActivity.class);
        startActivity(intent);
        Toast.makeText(MainActivityWC.this, "退出登录", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn:
                intent = new Intent(MainActivityWC.this, InfoActivity.class);
                startActivity(intent);
                break;
            case R.id.comment_btn:
                intent = new Intent(MainActivityWC.this, MsgTestActivity.class);
                startActivity(intent);
                break;
            case R.id.test_Tab_Btn:
//                intent = new Intent(MainActivityWC.this, TabViewPagerActivity.class);
//                startActivity(intent);
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Bitmap bitmap = null;
//                            try {
//                                bitmap = ImgDownUtil.Bytes2Bimap(ImgDownUtil.getImageBytes("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg"));
//                                Bitmap finalBitmap = bitmap;
//                                runOnUiThread(new Runnable() {
//                                    @RequiresApi(api = Build.VERSION_CODES.M)
//                                    @Override
//                                    public void run() {
//                                        assert finalBitmap!=null;
//                                        imageView.setImageIcon(Icon.createWithBitmap(finalBitmap));
//                                    }
//                                });
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//
//                        }
//                    }).start();

                new Thread(new PlayUserImg("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg",handler)).start();
                break;
            case R.id.test_more_detail_Btn:
//                intent = new Intent(MainActivityWC.this, UserDetailActivity.class);
//                intent.putExtra("detailUserName", "userName");
//                intent.putExtra("detailUserId", "userId");
//                startActivity(intent);
                TestDefineMessage.sendTeamMessage("xxxxx队伍删除了提示消息", "1234");
                break;
            case R.id.main_query_btn:
//                intent = new Intent(MainActivityWC.this, TestCameraActivity.class);
//                startActivity(intent);
                TestDefineMessage.sendTeamMessage("诚邀您加入我们的队伍", "1234");
                break;
            default:
                break;
        }
    }

    //以下代码实现下载图片并设置相应的imageview显示
    //new Thread(new PlayUserImg("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg",handler)).start();
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PlayUserImg.PLAYIMG_IS_FAILED:
                    break;
                case PlayUserImg.PLAYIMG_IS_FINISH:
                    imageView.setImageIcon(Icon.createWithBitmap((Bitmap)msg.obj));
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 这里用来实现,再点一次返回键退出应用,应该放在首先进入的页面
     *
     * @param keyCode
     * @param event
     * @return
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private String createNotificationChannel(String channelID, String channelNAME, int level) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
            manager.createNotificationChannel(channel);
            return channelID;
        } else {
            return null;
        }
    }

    private static final String FORMATER = "yyyy:MM:dd:HH:mm:ss";

    /**
     * 生成当前时间                        <br>
     */
    public static String genCurrentTime() {
        SimpleDateFormat formater = new SimpleDateFormat(FORMATER);
        return formater.format(new Date());
    }


//    Intent intent = new Intent(SplashActivity.this,ChatActivity.class);
//    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
//    Notification notification;
//    Notification.Builder builder;
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//        builder=new Notification.Builder(this,"5996773");
//    }else {
//        builder=new Notification.Builder(this);
//    }
//    //设置标题
//                builder.setContentTitle("设置标题");
//    //设置内容
//                builder.setContentText("内容是............");
//    //设置状态栏显示的图标，建议图标颜色透明
//                builder.setSmallIcon(R.mipmap.ic_launcher);
//    // 设置通知灯光（LIGHTS）、铃声（SOUND）、震动（VIBRATE）、（ALL 表示都设置）
//                builder.setDefaults(Notification.DEFAULT_ALL);
//    //灯光三个参数，颜色（argb）、亮时间（毫秒）、暗时间（毫秒）,灯光与设备有关
//                builder.setLights(Color.RED, 200, 200);
//    // 铃声,传入铃声的 Uri（可以本地或网上）我这没有铃声就不传了
//                builder.setSound(Uri.parse("")) ;
//    // 震动，传入一个 long 型数组，表示 停、震、停、震 ... （毫秒）
//                builder.setVibrate(new long[]{0, 200, 200, 200, 200, 200});
//    // 通知栏点击后自动消失
//                builder.setAutoCancel(true);
//    // 简单通知栏设置 Intent
//                builder.setContentIntent(pendingIntent);
//                builder.setPriority(Notification.PRIORITY_HIGH);
//
//    //设置下拉之后显示的图片
//                builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//        NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
//        channel.enableLights(true);//是否在桌面icon右上角展示小红点
//        channel.setLightColor(Color.GREEN);//小红点颜色
//        channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
//        mNManager.createNotificationChannel(channel);
//    }
//    notification=builder.build();
//                mNManager.notify(1,notification);

    @Override
    public void onMessageReceived(List<EMMessage> list) {
        Log.e(TAG, "xiaoxi");
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        for (EMMessage message : list) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String messageType = "chatMessage";
                    Log.e("MWC上", messageType);
                    //team操作通知消息类型（邀请入队、删除队伍通知）
                    messageType = message.getStringAttribute(TestDefineMessage.TEAM_NOTIFICATION, "chatMessage");
                    Log.e("MWC", messageType);
                    Log.e("MWC下", messageType);
                    //默认是聊天消息类型
                    if (TestDefineMessage.TEAM_NOTIFICATION_INVITE.equals(messageType)) {
                        Log.e("MWC", "收到队伍消息" + ((EMTextMessageBody) message.getBody()).getMessage());
                        //收到了队伍相关通知的消息(邀请入队以及删除队伍时的提示)
                        String userId = message.getUserName();//发送邀请入队请求的userId
                        TeamNotification teamNotification = new TeamNotification(userId, ((EMTextMessageBody) message.getBody()).getMessage(), accountId, TestDefineMessage.TEAM_NOTIFICATION_INVITE);
                        teamNotificationViewModel.insertTeamNotification(teamNotification);
                    } else if (TestDefineMessage.TEAM_NOTIFICATION_DELETE.equals(messageType)) {
                        //收到了队伍相关通知的消息(删除队伍时的提示)
                        String userId = message.getUserName();//发送邀请入队请求的userId
                        TeamNotification teamNotification = new TeamNotification(userId, ((EMTextMessageBody) message.getBody()).getMessage(), accountId, TestDefineMessage.TEAM_NOTIFICATION_DELETE);
                        teamNotificationViewModel.insertTeamNotification(teamNotification);
                    } else {
                        Intent intent = new Intent(MainActivityWC.this, MsgTestActivity.class);
                        intent.putExtra("chatUserId", message.getUserName());
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityWC.this, 0, intent, 0);
                        String channelId = createNotificationChannel("my_channel_ID", "my_channel_NAME", NotificationManager.IMPORTANCE_HIGH);
                        Notification.Builder notification;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            notification = new Notification.Builder(MainActivityWC.this, "5996773");
                        } else {
                            notification = new Notification.Builder(MainActivityWC.this);
                        }

                        //NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivityWC.this, channelId)
                        notification
                                //设置标题
                                .setContentTitle(message.getFrom() + "发来一条消息")
                                //设置内容
                                .setContentText(((EMTextMessageBody) message.getBody()).getMessage())
                                //设置状态栏显示的图标，建议图标颜色透明
                                .setSmallIcon(R.mipmap.ic_launcher)
                                // 设置通知灯光（LIGHTS）、铃声（SOUND）、震动（VIBRATE）、（ALL 表示都设置）
                                .setDefaults(Notification.DEFAULT_ALL)
                                //灯光三个参数，颜色（argb）、亮时间（毫秒）、暗时间（毫秒）,灯光与设备有关
                                .setLights(Color.RED, 200, 200)
                                // 铃声,传入铃声的 Uri（可以本地或网上）我这没有铃声就不传了
                                .setSound(Uri.parse(""))
                                // 震动，传入一个 long 型数组，表示 停、震、停、震 ... （毫秒）
                                .setVibrate(new long[]{0, 200, 200, 200, 200, 200})
                                // 通知栏点击后自动消失
                                .setAutoCancel(true)
                                // 简单通知栏设置 Intent
                                .setContentIntent(pendingIntent)
                                .setPriority(Notification.PRIORITY_HIGH);
//                            .setContentTitle(message.getFrom())
//                            .setContentText("收到一条消息")
//                            .setWhen(System.currentTimeMillis())//通知栏显示时间
//                            .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
//                            .setSmallIcon(R.mipmap.ic_launcher)//通知栏小图标
//                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//通知栏下拉是图标
//                            .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
//                            .setPriority(NotificationCompat.PRIORITY_MAX)//设置通知消息优先级
//                            .setAutoCancel(true)//设置点击通知栏消息后，通知消息自动消失
//                            .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.message_arrive))
//                            .setVibrate(new long[]{0, 1000, 1000, 1000})
////                .setSound(Uri.fromFile(new File("/system/MP3/music.mp3"))) //通知栏消息提示音
////                            .setVibrate(new long[]{0, 1000, 1000, 1000}) //通知栏消息震动
////                            .setLights(Color.GREEN, 1000, 2000) //通知栏消息闪灯(亮一秒间隔两秒再亮)
////                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) //通知栏提示音、震动、闪灯等都设置为默认
//                            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
////                            .setStyle(new NotificationCompat.InboxStyle()
////                                    .addLine(((EMTextMessageBody) message.getBody()).getMessage()))
//                            .setAutoCancel(true)
//                            .setStyle(new Notification().BigTextStyle().
//                                    bigText(((EMTextMessageBody) message.getBody()).getMessage()));

                        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivityWC.this);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
                            channel.enableLights(true);//是否在桌面icon右上角展示小红点
                            channel.setLightColor(Color.GREEN);//小红点颜色
                            channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
                            notificationManager.createNotificationChannel(channel);
                        }
                        notificationManager.notify(100, notification.build());
                        Msg msg = new Msg(((EMTextMessageBody) message.getBody()).getMessage(), Msg.TYPE_RECEIVED, message.getUserName(), accountId, genCurrentTime());
//                    Message message1 = new Message(message.getUserName(),((EMTextMessageBody) message.getBody()).getMessage(),accountId,Msg.TYPE_RECEIVED,genCurrentTime());
//                    messageViewModel.insertMessage(message1);
                        db.execSQL("insert into chatDb(userId,toUserId,content,type,time) values(?,?,?,?,?)"
                                , new String[]{msg.getUserId(), msg.getToUserId(), msg.getContent(), String.valueOf(msg.getType()), msg.getTime()});
                        Log.e("MainWc", "存储一条消息" + ((EMTextMessageBody) message.getBody()).getMessage());
                        if (!isExistUserIdInfo(message.getUserName())) {
                            //不存在与userId用户的对话框插入
                            Info info = new Info(message.getUserName(), ((EMTextMessageBody) message.getBody()).getMessage(), message.getUserName(), accountId, 1);
                            Log.e("MainWc", "创建新的对话窗口");
                            infoViewModel.insertInfo(info);
                            //以下是没有使用ViewModel的对话框，现在只是用来作为一个判断本地是否已经有此对话框使用，跟着ViewModel的对话框一起存本地sqlite(但是是不同的数据库）
                            db.execSQL("insert into infoItem(userId,userName,lastInfo,ownerUserId) values(?,?,?,?)"
                                    , new String[]{message.getUserName(), message.getUserName(), ((EMTextMessageBody) message.getBody()).getMessage(), accountId});
                        } else {//存在只需修改最新一条消息即可
                            infoViewModel.lastInfoAndInfoNum(((EMTextMessageBody) message.getBody()).getMessage(), message.getUserName(), accountId);
                            Log.e("MainWc", "原有窗口基础上修改信息");
                            //                        db.execSQL("update infoItem set lastInfo = ? where userId = ? and ownerUserId =?"
//                                , new String[]{((EMTextMessageBody) message.getBody()).getMessage(), message.getUserName(),accountId});
                        }
                        Log.e("消息的用户名", message.getUserName());
                    }


                }
            });
        }
        //此处可以写保存聊天信息到本地数据库
        //环信导入消息到数据库（对于消息，环信sdk会自动创建本地数据库) 但是没用到
        EMClient.getInstance().chatManager().importMessages(list);
    }

    /**
     * 判断数据库是否存在与userId用户的对话框
     *
     * @param userId id
     * @return 存在true 否则false
     */
    private boolean isExistUserIdInfo(String userId) {
//        return infoViewModel.isExistInfo(userId,accountId);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select userName from infoItem where userId = ? and ownerUserId=?"
                , new String[]{userId, accountId});
        if (cursor.moveToFirst()) {//查出来数据表示存在与userId用户的对话框了
            return true;
        }
        return false;
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }


    @Override
    protected void onResume() {
        super.onResume();
        //注册消息监听
        EMClient.getInstance().chatManager().addMessageListener(this);
        //注册好友监听
        EMClient.getInstance().contactManager().setContactListener(this);
    }


//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        //注册消息监听
//        EMClient.getInstance().chatManager().addMessageListener(this);
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消好友监听
        EMClient.getInstance().contactManager().removeContactListener(this);

    }

    @Override
    public void onContactAdded(String s) {
        //增加联系人时回调此方法
    }

    @Override
    public void onContactDeleted(String s) {
        //被删除时回调此方法
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onContactInvited(String s, String s1) {
        //收到好友邀请 s 用户id  s1 reason
        Intent intent = new Intent(MainActivityWC.this, InfoActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityWC.this, 0, intent, 0);
        String channelId = createNotificationChannel("my_channel_ID", "my_channel_NAME", NotificationManager.IMPORTANCE_HIGH);
        assert channelId != null;
        NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivityWC.this, channelId)
                .setContentTitle(s + ":申请添加好友，快来看看吧！")
                //.setContentText("好友申请，快来看看吧！")
                .setWhen(System.currentTimeMillis())//通知栏显示时间
                .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
                .setSmallIcon(R.mipmap.ic_launcher)//通知栏小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//通知栏下拉是图标
                .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
                .setPriority(NotificationCompat.PRIORITY_MAX)//设置通知消息优先级
                .setAutoCancel(true)//设置点击通知栏消息后，通知消息自动消失
//                .setSound(Uri.fromFile(new File("/system/MP3/music.mp3"))) //通知栏消息提示音
                .setVibrate(new long[]{0, 1000, 1000, 1000}) //通知栏消息震动
                .setLights(Color.GREEN, 1000, 2000) //通知栏消息闪灯(亮一秒间隔两秒再亮)
                .setDefaults(NotificationCompat.DEFAULT_ALL) //通知栏提示音、震动、闪灯等都设置为默认
                .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setStyle(new NotificationCompat.InboxStyle().addLine(s1))
                .setAutoCancel(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivityWC.this);
        notificationManager.notify(100, notification.build());

//        Apply apply = new Apply();

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        HttpUtils httpUtils = HttpUtils.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("userId", s);
        FormBody formBody = builder.build();
        httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserNameByIdServlet", formBody, new HttpUtils.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(Request request, String result) {
                Gson gson = new Gson();
//                        JsonObject resultJson = gson.fromJson(result, JsonObject.class);
//                        JsonElement jsonElement = resultJson.get("state");
//                        Log.e("login Result ",resultJson.toString());
//                        if (jsonElement.getAsString().equals("success"))
                JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                JsonElement jsonElement = resultJson.get("userName");
                String userName = jsonElement.getAsString();
                db.execSQL("insert into notification(userId,userName,applyContent) values(?,?,?)"
                        , new String[]{s, userName, s1});

                Apply apply = new Apply(userName, s, s1, accountId);
                applyViewModel.insertApply(apply);
                Log.e("MainActivityWc", "根源获取好友昵称！.");
                Log.e("MainActivityWcName", userName);
            }
        });

    }

    @Override
    public void onFriendRequestAccepted(String s) {
        //好友请求被同意
        HttpUtils httpUtils = HttpUtils.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("userId", s);
        FormBody formBody = builder.build();
        httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserNameByIdServlet", formBody, new HttpUtils.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @Override
            public void onSuccess(Request request, String result) {
                Gson gson = new Gson();
                JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                JsonElement jsonElement = resultJson.get("userName");
                String userName = jsonElement.getAsString();
                Friend friend = new Friend(userName, s, accountId);
                friendViewModel.insertFriend(friend);
                Log.e("MainWc", "本地保存好友信息成功.");
            }
        });

//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        db.execSQL("insert into friend(userId,userName) values(?,?)",new String[]{s,s});
    }

    @Override
    public void onFriendRequestDeclined(String s) {
        //好友请求被拒绝
    }
}
